/**
 * Funkcja odpowiada za zwijanie i rozwijanie menu bocznego użytkowników
 */
function navShowHide() {

	$('#show_hide').click(function() {
		$('ul.top-nav').slideToggle('slow', function() {
			if ($('ul.top-nav').is(":visible")) {
				$('#show_hide').text("Ukryj menu << ");
			} else {
				$('#show_hide').text("Pokaż menu >> ");
			}
			$('ul.top-nav > li').toggleClass('#nav ul.top-nav > li');
		});
	});

	$('ul.top-nav > li').click(
			function() {
				$('ul.top-nav > li:hover > ul').slideToggle(
						'fast',
						function() {
							if ($('ul.sub-nav > li').is(":visible")) {
								$('ul.top-nav > li:active').toggleClass(
										'#nav top-nav_hover');
							}
							if ($('ul.sub-nav > li').not(":visible")) {
								$('ul.top-nav > li:active').toggleClass(
										'#nav ul.top-nav > li');
							}

						});
			});
}
/**
 * Metoda zamieniająca wszystkie plusy występujące w parametrze na spacje
 */

function replaceAll(source, stringToFind, stringToReplace) {
	var temp = source;
	var index = temp.indexOf(stringToFind);
	while (index != -1) {
		temp = temp.replace(stringToFind, stringToReplace);
		index = temp.indexOf(stringToFind);
	}
	return temp;
}
/**
 * Metoda pobierająca wartość parametru z linka
 */
function getParameterName(link, nameParameter) {
	var index = link.indexOf(nameParameter);
	var startIndex = index + nameParameter.length + 1;
	var parameterValue = '';
	while (link.charAt(startIndex) != "/") {
		parameterValue = parameterValue + link.charAt(startIndex);
		startIndex++;
	}

	return replaceAll(parameterValue, '+', ' ');

}

/**
 * Okienko alert upewniające się czy na pewno użytkownik chce usunąć rekord z
 * bazy danych
 */

function deleteRecord() {
	$(".delete").click(
			function() {
				var link = $(this).attr('href');
				var newLink = link.replace("jsflag/false", "jsflag/true");
				console.log($(this).attr('href'));
				var parameterValue = getParameterName(decodeURI(link), 'name');
				var communicat = 'Czy napewno chcesz usunąć rekord \"'
						+ parameterValue.bold() + '\" ?';
				var confirm = 'Rekord \"' + parameterValue.bold()
						+ '\" został poprawnie usunięty.';
				apprise(communicat/* .fontcolor("red") */, {
					'verify' : true
				}, function(deleteRow) {
					if (deleteRow) {

						$.ajax({
							url : newLink,
							type : 'GET',
							success : function(data) {
								window.location.reload();
							/*	
								apprise(confirm, {
									'verify' : false
								}, function(deleteSuccess) {
									if (deleteSuccess) {
										window.location.reload();
									} else {
									}

								});
								*/
							}
						});

					} else {

					}
				});

				return false;

			});

}


function editRecord() {
	
	$("#dialog-form").validationEngine('validate');
	$("#dialog-form").validationEngine({
		promptPosition : "centerRight",
		scroll : true
	});

	$("#dialog-form").dialog({
		autoOpen : false,
		height : 300,
		width : 520,
		modal : true,
		buttons : {
			Cancel : function() {
				$(this).dialog("close");
			}
		},
		close : function() {
		}

	});
	$("#cancelOrder").click(function() {
		$("#dialog-form").dialog("close");

	});
	$(".edit").click(
			function() {
				var link = $(this).attr('href');
				console.log($(this).attr('href'));
				var parameterValue = getParameterName(decodeURI(link), 'name');
				var communicat = 'Czy napewno chcesz edytować rekord \"'
					+ parameterValue.bold() + '\" ?';
				var confirm = 'Rekord został poprawnie zaktualizowany.';
				apprise(communicat/* .fontcolor("red") */, {
					'verify' : true
				}, function(editRow) {
					if (editRow) {

						$.ajax({
							url : link,
							type : 'GET',
							success : function(data) {
								$("#dialog-form").dialog("open");
								$("#dialog-form").load(link);
							}
						});

					} else {

					}
				});

				return false;

			});
}


function addRecord() {
	//$("#").validationEngine('detach');
	$("#add-dialog-form").validationEngine('validate');
	$("#add-dialog-form").validationEngine({
		promptPosition : "centerRight",
		scroll : true
	});

	$("#add-dialog-form").dialog({
		autoOpen : false,
		height : 300,
		width : 520,
		modal : true,
		buttons : {
			Cancel : function() {
				$(this).dialog("close");
			}

		},

		close : function() {
		}

	});
	$("#cancelOrder").click(function() {
		$("#add-dialog-form").dialog("close");

	});
	$(".add").click(function() {
		var link = $(this).attr('href');
		var communicat = 'Czy napewno chcesz dodać nowy rekord ?';
		apprise(communicat/* .fontcolor("red") */, {
			'verify' : true
		}, function(addRow) {
			if (addRow) {
				$.ajax({
					url : link,
					type : 'GET',
					success : function(data) {
						$("#add-dialog-form").dialog("open");
						$("#add-dialog-form").load(link);
					}
				});

			} else {

			}
		});

		return false;
	});

}

function addNewSubjectInOrder() {

		$("#dialog-form").validationEngine('validate');
		$("#dialog-form").validationEngine({
			promptPosition : "centerRight",
			scroll : true
		});

		$("#dialog-form").dialog({
			autoOpen : false,
			height : 300,
			width : 520,
			modal : true,
			buttons : {
				Cancel : function() {
					$(this).dialog("close");
				}

			},

			close : function() {
			}

		});
		$("#cancelOrder").click(function() {
			$("#dialog-form").dialog("close");

		});

		$(".addSubjectInOrder").click(function() {
			var link = $(this).attr('href');
			$("#dialog-form").dialog("open");
			$("#dialog-form").load(link);

			return false;
		});
}


/**
 * Odpowiada za znikanie tekstu z komunikatem o wykonanej operacji usuwania
 * rekordu
 */
function disappearingContent10000(classname) {
	setTimeout(function() {
		$(classname).hide();
	}, 10000);
}

/**
 * Zaznaczanie/odznaczanie wszystkich checkbox`ow przy masowych zdarzeniach
 */
function showAllCheckAll() {
	$(function() {
		$('input[name="checkedAll"]').click(
				function() {
					this.checked ? $('.all').attr('checked', true) : $('.all')
							.attr('checked', false);
				});
	});
}

/**
 * Sprawdza czy podana wartość jest liczbą
 */
function isInt(x) { 
	  var y=parseInt(x); 
	  if (isNaN(y)) return false; 
	  return x==y && x.toString()==y.toString(); 
}
/**
 * Pobiera liczbę pól
 */
function getNumberFields(idField) {
	var numberFields = $(idField).val();
	if( isInt(numberFields) ) 
		return numberFields;
	else 
		return 0;
	  
}
/**
 * Dodaje nowe dynamiczne pola do formularza w zależności od podanej wartości
 */


function addNewFields() {
	//$.removeData($('#zendForm'),'validator');
	//$('#zendForm').validation();
    $('#groupLectureNumber').change( function(){


    	var numberOfFields = getNumberFields('#groupLectureNumber');
    	for(var i=1; i<= numberOfFields; i++){
    		var input = "<dt><label for=\"groupLectureName" + i + "\" class=\"required\">Nazwa grupy wykładowej " + i + "</label></dt>" +
    		"<dd><input type=\"text\" name=\"groupLectureName" + i + "\" id=\"groupLectureName" + i + "\" value=\"\" size=\"30\" class=\"validate[required]\"/></dd>" +
    		"<dt><label for=\"groupLectureNumberStudents" + i + "\" class=\"required\">Liczebność grupy wykładowej " + i + "</label></dt>" +
    		"<dd><input type=\"text\" name=\"groupLectureNumberStudents" + i + "\" id=\"groupLectureNumberStudents" + i + "\" value=\"\" size=\"30\" class=\"validate[required]\" /></dd>";
    		$('#groupLaboratoryNumber-label').before(input);
    	}
    });
     
    $('#groupLaboratoryNumber').change( function(){
    	//$.removeData($('#zendForm'),'validator');
    	//$('#zendForm').validation();
    	var numberOfFields = getNumberFields('#groupLaboratoryNumber');
    	for(var i=1; i<= numberOfFields; i++){
    		var input = "<dt><label for=\"groupLaboratoryName" + i + "\" class=\"required\">Nazwa grupy laboratoryjnej " + i + "</label></dt>" +
    			"<dd><input type=\"text\" name=\"groupLaboratoryName" + i + "\" id=\"groupLaboratoryName" + i + "\" value=\"\" size=\"30\" class=\"validate[required]\" /></dd>" +
    			"<dt><label for=\"groupLaboratoryNumberStudents" + i + "\" class=\"required\">Liczebność grupy laboratoryjnej " + i + "</label></dt>" +
    			"<dd><input type=\"text\" name=\"groupLaboratoryNumberStudents" + i + "\" id=\"groupLaboratoryNumberStudents" + i + "\" value=\"\" size=\"30\" class=\"validate[required]\" /></dd>";
    		$('#groupExerciseNumber-label').before(input);
    	}
    });
    
   
    
    $('#groupExerciseNumber').change( function(){
    	//$.removeData($('#zendForm'),'validator');
    	//$('#zendForm').validate();
    	var numberOfFields = getNumberFields('#groupExerciseNumber');
    	for(var i=1; i<= numberOfFields; i++){    
    		var input = "<dt><label for=\"groupExerciseName" + i + "\" class=\"required\">Nazwa grupy ćwiczeniowej " + i + "</label></dt>" +
    			"<dd><input type=\"text\" name=\"groupExerciseName" + i + "\" id=\"groupExerciseName" + i + "\" value=\"\" size=\"30\" class=\"validate[required]\" /></dd>" +
    			"<dt><label for=\"groupExerciseNumberStudents\" class=\"required\">Liczebność grupy ćwiczeniowej " + i + "</label></dt>" +
    			"<dd><input type=\"text\" name=\"groupExerciseNumberStudents" + i + "\" id=\"groupExerciseNumberStudents" + i + "\" value=\"\" size=\"30\" class=\"validate[required]\" /></dd>";
    		$('#submit-label').before(input);
    	}
    });
}

  function sendParameter() {
	    $('#faculty_id').change( function(){
	    	//$.removeData($('#zendForm'),'validator');
	    	//$('#zendForm').validate();
	    	var valueOfField = $('#faculty_id').val();
	    	var parameters = "facultyparam=true&faculty=" + valueOfField + "";
	    	$.ajax({
	    		  type: 'POST',
	    		  url: '/dydack/public/technical/year/get',
	    		  data: parameters,
	    		  dataType : 'json',
	    		  success: function(data) { 
	    			  var input = "<dt><label for=\"cathedral_id\" class=\"required\">Na katedrze</label></dt><dd><select name=\"cathedral_id\" id=\"cathedral_id\" class=\"validate[required]\">";
	    			  for (key in data) {
	    				  input = input + "<option value=\"" + key + "\" label=\"" +  data[key] +"\">" + data[key] + "</option>";
	    			  }
	    			  input = input + "</select></dd>"; 
	    			  $('#tutor_id-label').before(input);
	    		  }
	    		  
	    		});
	    });
  }

  function displayConfirmAlert(status,confirm) {
		 if( status == 'updatesuccess' || status == 'deletesuccess' || status == 'addsuccess'){
				apprise(confirm, {
					'verify' : false
				});
		 } else if( status == 'updatefail' || status == 'deletefail' || status == 'fail') {
				apprise("Dane w bazie pozostały niezmienione.", {
					'verify' : false
				});
		 } else {
			 //nie rob nic bo bedzie wyswietlalo alerty niepotrzebie :)
		 }
  }
  function getDataForOrder (param, callback){
	  var temp;
	  $.ajax({
  		  type: 'POST',
  		  url: '/dydack/public/technical/order/get',
  		  data: param,
  		  async: false,
  		  dataType : 'json',
  		  success: function(data) {
  			 temp = data;  
  		  }
	  });
	  return temp;
  }
  function addFieldsToOrder() {
	 var courses = getDataForOrder("orderparam=course");
	 var lecturer = getDataForOrder("orderparam=lecturer");
	 var contentCheckboxId;
	 var nextContentCheckboxId;
		  $(".coursesTypeid").change(function() {
			  contentCheckboxId = $(this).attr("id");
			  var x = $(this).prev().attr('id');
			  //console.log(this);
			  //console.log($(this));
			  nextContentCheckboxId = $(this).parent().next().next().children(':first').attr('id');
			  if(document.getElementById( contentCheckboxId).checked) {
				  $("#zendForm").validationEngine('detach');
				  $('div').remove(".selector-" + contentCheckboxId);
				  
				  var input = "<div class=\"selector-" + contentCheckboxId + "\"><dt><label for=\"" + contentCheckboxId + "-lecture\" class=\"required\">Zajęcia:</label></dt><dd>" +
				  		"<select name=\"" + contentCheckboxId + "-lecture\" id=\"" + contentCheckboxId + "-lecture\" class=\"validate[required]\">";
				  for (key in courses) {
					  input = input + "<option value=\"" + key + "\" label=\"" +  courses[key] +"\">" + courses[key] + "</option>";
				  }
				  input = input + "</select></dd>"; 

				  input = input + "<div class=\"numberSelector-" + contentCheckboxId + "\"><dt><label for=\"" + contentCheckboxId + "-numberGroups\" class=\"required\">Ilość grup:</label></dt>" +
		  							"<dd><input type=\"text\" name=\"" + contentCheckboxId + "-numberGroups\" id=\"" + contentCheckboxId + "-numberGroups\" value=\"\" size=\"30\"class=\"validate[required,custom[onlyNumberSp]]\" /></div>";
				  
				  input = input + "<dt id = \"" + contentCheckboxId + "-PerWeek-label\" ><label for=\"" + contentCheckboxId + "-PerWeek\" class=\"required\">Ilość zajęć w tygodniu:</label></dt>" +
				  				  "<dd><input type=\"text\" name=\"" + contentCheckboxId + "-PerWeek\" id=\"" + contentCheckboxId + "-PerWeek\" value=\"\" size=\"30\"class=\"validate[required,custom[onlyNumberSp]]\" />" +
				  				  "</dd><dt><label for=\"" + contentCheckboxId + "-PerSemester\" class=\"required\">Ilość zajęć w semestrze:</label></dt>" +
				  				  "<dd><input type=\"text\" name=\"" + contentCheckboxId + "-PerSemester\" id=\"" + contentCheckboxId + "-PerSemester\" value=\"\" size=\"30\"class=\"validate[required,minSize[2],custom[onlyNumberSp]]\" />" +
				  				  "</div>";
				  
		
				  $("#" + nextContentCheckboxId + "-label").before(input);
				  $("#zendForm").validationEngine({
						promptPosition : "centerRight",
						scroll : true
					});
				  
				    $("#" + contentCheckboxId + "-numberGroups").change( function(){
				    	$('div').remove(".lecturerSelector-" + contentCheckboxId);
				    	$('div').remove(".groupSelector-" + contentCheckboxId);
				    	var numberOfFields = getNumberFields("#" + contentCheckboxId + "-numberGroups");
						$("#zendForm").validationEngine('detach');
						if ( numberOfFields == 0 ) {
					    	$('div').remove(".numberSelector-" + contentCheckboxId);
							var input = "<div class=\"lecturerSelector-" + contentCheckboxId + "\"><dt><label for=\"" + contentCheckboxId + "-lecturer\" class=\"required\">Prowadzący:</label></dt><dd><select name=\"" + contentCheckboxId + "-lecturer\" id=\"" + contentCheckboxId + "-lecturer\" class=\"validate[required]\">";
							  for (key in lecturer) {
								  input = input + "<option value=\"" + key + "\" label=\"" +  lecturer[key] +"\">" + lecturer[key] + "</option>";
							  }
							  input = input + "</select></dd></div>"; 
							  $("#" + contentCheckboxId + "-PerWeek-label").before(input);
							  $("#" + contentCheckboxId + "-lecturer").focus();
						} else {
					    	for(var i=1; i <= numberOfFields; i++){ 
					    		var input = "<div class=\"groupSelector-" + contentCheckboxId + "\"><dt><label for=\"group-" + contentCheckboxId + "-" + i + "\" class=\"required\">Grupa " + i + ":</label></dt>" +
						  			"<dd><input type=\"text\" name=\"group-" + contentCheckboxId + "-" + i + "\" id=\"group-" + contentCheckboxId + "-" + i + "\" value=\"\" size=\"30\"class=\"validate[required,minSize[2],maxSize[30]]\" /></dd>";
					    		
					    		input = input + "<dt><label for=\"lecturer-" + contentCheckboxId + "-" + i + "\" class=\"required\">Prowadzący " + i + ":</label></dt><dd><select name=\"lecturer-" + contentCheckboxId + "-" + i + "\" id=\"lecturer-" + contentCheckboxId + "-" + i + "\" class=\"validate[required]\">";
								  for (key in lecturer) {
									  input = input + "<option value=\"" + key + "\" label=\"" +  lecturer[key] +"\">" + lecturer[key] + "</option>";
								  }
								  input = input + "</select></dd></div>"; 
								  $("#" + contentCheckboxId + "-PerWeek-label").before(input);
					    	}
					    	$("#group-" + contentCheckboxId + "-1").focus();
						}
						$("#zendForm").validationEngine({
								promptPosition : "centerRight",
								scroll : true
						});
				    });  
				  
			  } else {
				$('div').remove(".selector-" + contentCheckboxId); 
			  }	  
		  });	   	  
  }	  
	  


